﻿using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text.RegularExpressions;

namespace RockBus.Subscription.Evaluators
{
    // Thanks to Roman Kiss:
    //  http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/3833bb46-7169-4697-9869-5ff3ec667113
    public class WildCardActionMessageFilter : MessageFilter
    {
        public string WildcardExpression { get; set; }

        public WildCardActionMessageFilter(string wildcardExpression)
        {
            this.WildcardExpression = wildcardExpression;
            string pattern = "^" + Regex.Escape(this.WildcardExpression).Replace(@"\*", ".*").Replace(@"\?", ".") + "$";
            this._regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        }

        private readonly Regex _regex;

        public override bool Match(Message message)
        {
            return InnerMatch(message.Headers.Action);
        }

        public override bool Match(MessageBuffer messageBuffer)
        {
            Message message = messageBuffer.CreateMessage();
            bool result;
            try
            {
                result = this.InnerMatch(message.Headers.Action);
            }
            finally
            {
                message.Close();
            }
            return result;
        }

        private bool InnerMatch(string action)
        {
            // I.e. for response messages, the Action can be null
            if (string.IsNullOrEmpty(action))
            {
                return false;
            }

            return this._regex.IsMatch(action);
        }
    }
}